﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Forging2.Common.Heating
{
    public class HeatingFurnace : Equipment, IHeatingFurnace
    {
        public int Count { get; set; }
        public string Temperatures { get; set; }
               
        public HeatingFurnace(string gid)
        {

        }

        public Task<dynamic> GetTemperatures(string FurnaceGID, string PLCAddressGID)
        {
            //获取单个温度数据意义不大，暂不实现。
            throw new NotImplementedException();
        }       

        /// <summary>
        /// 获取炉内数量
        /// </summary>
        public Task<int> GetInFurnaceCount()
        {
            var workcellcode = "";
            //0#炉未接入MES时处理
            workcellcode = CODE == "JRL0" ? "WL0051" : Const.IGDataDbContext.bas_equipment_zy.Find(GID).WORK_CELL_CODE;
            var heatingcount = from uvr in Const.ZH_IMESDbContext.uex_vtrack_record
                               join ufhr in Const.ZH_IMESDbContext.uex_furnace_handle_record on uvr.GID equals ufhr.VTRACK_RECORD_GID
                               where uvr.WORK_CELL_GID == Const.ZH_IMESDbContext.pmbf_work_cell.Where(wc => wc.CODE == workcellcode).FirstOrDefault().GID && ufhr.IS_DELETE != 1 && uvr.IS_DELETE != 1 && uvr.UDA1 == "1"
                               select uvr.UDA3;
            Count = heatingcount.Count();
            Console.WriteLine(string.Format("WorkCellCode: {1} GID: {0} ", GID, workcellcode));

            return Task.FromResult(Count);
            //var taskcount =await GetInFurnaceCountAsync();
            //Count = taskcount;
            }
           
       

        public Task<dynamic> InFurnace(WorkingPiece workpiece ,string areacode)
        {
            throw new NotImplementedException();
        }

        public  Task<dynamic> OutFurnace(WorkingPiece workpiece)
        {
            var msg = "";
            var uvr = Const.v_ForgingOperateDatas.Where(v => v.ForgingNO == workpiece.ForgingNO && Const.Config.FurnaceWorkCells.Contains(v.WORKCELL_CODE)).FirstOrDefault();
            if (uvr !=null)
            {
                var ufhr = Const.ZH_IMESDbContext.uex_furnace_handle_record.Where(ur => ur.VTRACK_RECORD_GID == uvr.GID).FirstOrDefault();
                if (ufhr != null)
                {
                    ufhr.TYPE = 2;
                    ufhr.HEAT_COUNT++;
                    ufhr.OUT_TIME = DateTime.Now;
                    ufhr.MODIFY_DATE = DateTime.Now;

                    uvr.InFurnace = "0";
                    uvr.MODIFY_DATE = DateTime.Now;
                    msg = string.Format("锻件编号 {0} 出炉操作完成！", workpiece.ForgingNO);
                    return Task.FromResult<dynamic>(msg);
                }
            }
            msg = "未找到相应的锻件，出炉操作失败！" ;
            return Task.FromResult<dynamic>(msg);
        }
         
        public async Task DisplayTemperatures()
        {
             await Task.Run(DisplayTemperatures);
            //throw new NotImplementedException();
        }

        public void DisplayTemperatures(System.Windows.Controls.TextBlock textBlock)
        {
            if (textBlock.Dispatcher.CheckAccess())
            {
                textBlock.Text = Temperatures.ToString();                
            }
            else
            {
                textBlock.Dispatcher.Invoke(new Action(() => { textBlock.Text = Temperatures.ToString(); }));
            }

        }

        public void DisplayCount(System.Windows.Controls.TextBlock textBlock)
        {
            if (textBlock.Dispatcher.CheckAccess())
            {
                textBlock.Text = Count.ToString();
            }
            else
            {
                textBlock.Dispatcher.Invoke(new Action(() => { textBlock.Text = Count.ToString(); }));
            }

        }

      
        /// <summary>
        /// 炉内工单信息
        /// </summary>
        /// <returns></returns>
        public List<HeatingWorkpiece> GetInFurnaceWorkpiece()
        {
            var data = Const.ZH_IMESDbContext;
            //var infurncaeworkpiece = data.Database.SqlQuery<HeatingWorkpiece>("SELECT GID,DISPATCH_CODE,PRODU_CODE,CREATE_DATE FROM v_jrl_infurnace");
            var infurncaeworkpiece = data.Database.SqlQuery<HeatingWorkpiece>(Const.Config.InFurnaceQuery);
            Console.WriteLine(infurncaeworkpiece.Count());
            return infurncaeworkpiece.ToList<HeatingWorkpiece>();
        }
        /// <summary>
        /// 炉外工单信息
        /// </summary>
        /// <returns></returns>
        public List<HeatingWorkpiece> GetOutFurnaceWorkpiece()
        {
            var data = Const.ZH_IMESDbContext;
            var outfurncaeworkpiece = data.Database.SqlQuery<HeatingWorkpiece>(Const.Config.OutFurnaceQuery);
            Console.WriteLine(outfurncaeworkpiece.Count());
            return outfurncaeworkpiece.ToList<HeatingWorkpiece>();
        }
        /// <summary>
        /// 工件出炉
        /// </summary>
        /// <param name="heatingWorkpiece">炉内工件</param>
        /// <returns></returns>
        private Task<string> HeatingWorkPieceOutFurnace(WorkingPiece workpiece)
        {
            DataBase.ZH_IMES.uex_furnace_handle_record ufhr = Const.ZH_IMESDbContext.uex_furnace_handle_record.Where(fr => fr.VTRACK_RECORD_GID == workpiece.GID && fr.OUT_TIME == null && fr.TYPE == 1).FirstOrDefault();
            DataBase.ZH_IMES.uex_vtrack_record uvr = Const.ZH_IMESDbContext.uex_vtrack_record.FindAsync(workpiece.GID).Result;

            if (ufhr is null || uvr is null)
            {
                Const.Front.ErrorNotification = "后台【出炉】数据有问题，与管理员联系！";
                return Task.FromResult("");
            }
            ufhr.TYPE = 2;
            ufhr.HEAT_COUNT++;
            ufhr.OUT_TIME = DateTime.Now;
            ufhr.MODIFY_DATE = DateTime.Now;

            uvr.UDA1 = "0";
            uvr.MODIFY_DATE = DateTime.Now;

            return Task.FromResult(workpiece.GID);           

        }
        /*************************************上面的代码还需优化********************************************************/
        public List<DataBase.ZH_IMES.V_ForgingOperateData> FurnaceOperateDatas;
        public List<DataBase.ZH_IMES.V_ForgingOperateData> GetForgingOperateDatas()
        {
            var workcells = Const.Config.WorkCells.ToArray<string>();
            FurnaceOperateDatas = Const.ZH_IMESDbContext.V_ForgingOperateData.Where(f => f.WORK_CENTER_GID == Const.Config.WorkCenter && workcells.Contains(f.WORKCELL_NAME) && f.DIS_CODE_STATE != 3).ToList<DataBase.ZH_IMES.V_ForgingOperateData>();
            return FurnaceOperateDatas;
        }

        public async Task<dynamic> StartHeating(HeatingWorkpiece workpiece)
        {
            DataBase.ZH_IMES.V_ForgingOperateData vdata = FurnaceOperateDatas.Find(v => v.GID == workpiece.GID) ;
            vdata.DIS_CODE_STATE = 1;
            vdata.MODIFY_DATE = DateTime.Now;
            vdata.MODIFY_ID = Const.Config.OperateCode;
            return await SaveHeatingFurnaceDatas(string.Format(" 加热工序，锻件号：{0} 开工完成！",workpiece.FORGING_NO));
            
        }

        public  Task<dynamic> HeatingCancel(HeatingWorkpiece workpiece)
        {
            return  null;
           /* 
            DataBase.ZH_IMES.V_ForgingOperateData vdata = FurnaceOperateDatas.Find(v => v.GID == workpiece.GID);
            vdata.DIS_CODE_STATE = 3;
            vdata.MODIFY_DATE = DateTime.Now;
            vdata.MODIFY_ID = Const.Config.OperateCode;
            if (Const.WorkClamping is null)
            {
                Const.WorkClamping = new Clamping.Clamping();
            }
            await Const.WorkClamping.FurnaceClamping(this, workpiece, workpiece.FURNACE_AREA);

            return await SaveHeatingFurnaceDatas(string.Format
                (" 加热工序，锻件号：{0} 完工完成！", workpiece.FORGING_NO));
            */
        }

        private Task<int> SaveHeatingFurnaceDatas(string msg)
        {
            var iret= Const.ZH_IMESDbContext.SaveChanges();
            Const.Front.Notification = msg + string.Format("  影响{0} 条数据。", iret);
            return Task.FromResult(iret);
        }


        
    }
}
